package com.example.springboot_response_exception.controller;

import com.example.springboot_response_exception.common.Result;
import com.example.springboot_response_exception.exception.BusinessException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 测试 Controller
 * 用于演示成功响应、业务异常和系统异常的处理
 */
@RestController
@RequestMapping("/api/test")
public class TestController {

    /**
     * 成功响应的端点
     * GET /api/test/success
     */
    @GetMapping("/success")
    public Result<Map<String, String>> getSuccessData() {
        Map<String, String> data = new HashMap<>();
        data.put("key", "value");
        data.put("message", "这是一个成功的响应");
        return Result.success(data);
    }

    /**
     * 触发业务异常的端点
     * GET /api/test/biz-error?name=admin
     */
    @GetMapping("/biz-error")
    public Result<Void> triggerBusinessException(@RequestParam String name) {
        if ("admin".equals(name)) {
            throw new BusinessException(4001, "用户名 'admin' 已被占用");
        }
        return Result.success();
    }

    /**
     * 触发空指针异常的端点
     * GET /api/test/npe-error
     */
    @GetMapping("/npe-error")
    public Result<Void> triggerNullPointerException() {
        String str = null;
        // 这将抛出 NullPointerException
        str.length();
        return Result.success();
    }

    /**
     * 触发通用异常的端点
     * GET /api/test/general-error
     */
    @GetMapping("/general-error")
    public Result<Void> triggerGeneralException() {
        throw new RuntimeException("这是一个通用的运行时异常");
    }
}